package zcw.com.lib_leet_code;

import zcw.com.lib_leet_code.util.Util;

/**
 * Created by 朱城委 on 2021-8-28.<br><br>
 *
 * 中等：下一个排列
 */
public class Topic31 {

    public static void main(String[] args) {
        Topic31 instance = new Topic31();

        int[] array = new int[] {1,2,3};
        instance.nextPermutation(array);
        Util.printArray(array);

        array = new int[] {3,2,1};
        instance.nextPermutation(array);
        Util.printArray(array);

        array = new int[] {1,1,5};
        instance.nextPermutation(array);
        Util.printArray(array);

        array = new int[] {1};
        instance.nextPermutation(array);
        Util.printArray(array);

        array = new int[] {1,3,2};
        instance.nextPermutation(array);
        Util.printArray(array);

        array = new int[] {4,2,0,2,3,2,0};
        instance.nextPermutation(array);
        Util.printArray(array);

        array = new int[] {1,5,1};
        instance.nextPermutation(array);
        Util.printArray(array);

        array = new int[] {5,1,1};
        instance.nextPermutation(array);
        Util.printArray(array);

        array = new int[] {1,1};
        instance.nextPermutation(array);
        Util.printArray(array);
    }

    public void nextPermutation(int[] nums) {
        int i = nums.length - 2;
        while (i >= 0 && nums[i] >= nums[i + 1]) {
            i--;
        }

        if(i >= 0) {
            int j = nums.length - 1;
            while (j >= 0 && nums[j] <= nums[i]) {
                j--;
            }

            swap(nums, i, j);
        }

        helper(nums, i + 1);
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    private void helper(int[] nums, int start) {
        int end = nums.length - 1;

        while (start < end) {
            swap(nums, start, end);

            start++;
            end--;
        }
    }
} 
